/*
 * @Description:
 * @Date: 2024-05-20 15:50:12
 * @LastEditTime: 2024-10-09 14:21:59
 */
const { SDK_VERSION } = require('../../lib/agora-miniapp-sdk.js')

Component({
  data: {
    version: SDK_VERSION,
  },
  created() { },
  onLoad() {
    this.channel = ''
    this.lock = false
  },
  methods: {
    join() {
      const value = this.channel || ''

      if (!value) {
        wx.showToast({
          title: '请提供一个有效的房间名',
          icon: 'none',
          duration: 2000,
        })
      } else {
        if (this.checkJoinLock()) {
          this.lockJoin()
          if (value === 'agora') {
            // go to test page if channel name is agora
            wx.navigateTo({
              url: `../test/test`,
            })
          } else {
            const url = 'https://yajcy.gov.cn:8082/app-api/pro/video/get/token'
            const { userInfo } = JSON.parse(wx.getStorageSync('user'))

            // 需要发送的数据
            const data = {
              channelName: this.channel,
            }

            // 将数据转换为查询字符串
            const postData = Object.keys(data)
              .map((key) => `${encodeURIComponent(key)}=${encodeURIComponent(data[key])}`)
              .join('&')

            wx.request({
              url,
              method: 'POST',
              header: {
                'Content-Type': 'application/x-www-form-urlencoded',
                Authorization: userInfo.token,
                'tenant-id': userInfo.tenantId,
              },
              data: postData,
              success(res) {
                wx.setStorage({
                  key: 'meetingToken',
                  data: res.data,
                  success() {
                    wx.showModal({
                      title: '是否推流',
                      content: '选择取消则作为观众加入，观众模式不推流',
                      showCancel: true,
                      success: function (res) {
                        let role = 'audience'
                        if (res.confirm) {
                          role = 'broadcaster'
                        }
                        wx.navigateTo({
                          url: `/pages/menu/videoCall/meeting?channel=${value}&&role=${role}`,
                        })
                      },
                    })
                  },
                })
              },
              fail(error) {
                console.error(error)
              },
            })
          }
        }
      }
    },
    /**
     * check if join is locked now, this is mainly to prevent from clicking join btn to start multiple new pages
     */
    checkJoinLock() {
      return !(this.lock || false)
    },

    lockJoin() {
      this.lock = true
    },

    unlockJoin() {
      this.setData({
        channel: '',
        lock: false,
      })
      this.channel = ''
      this.lock = false
    },

    onInputChannel(e) {
      const value = e.detail.value
      this.channel = value
    },
  },
})
